package com.xbongbong.paas.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.elasticsearch.model.PaasFormSubDataEsModel;
import com.xbongbong.paas.elasticsearch.pojo.XbbAggregatedPage;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.help.ProFormHelp;
import com.xbongbong.paas.help.analysis.data.FormDataLinkDataListAnalysisDataHelp;
import com.xbongbong.paas.pojo.dto.FormDataListDTO;
import com.xbongbong.paas.pojo.subform.dto.SubFormDataListDTO;
import com.xbongbong.paas.pojo.subform.vo.SubFormDataListVO;
import com.xbongbong.paas.pojo.vo.PaasFormDataEsListVO;
import com.xbongbong.paas.service.PaasSubFormDataService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.helper.PageHelper;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.PageHelperUtil;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.saas.constant.PageConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.model.IndexTypeModel;
import com.xbongbong.saas.util.OrganizationFieldUtil;
import com.xbongbong.sys.domain.entity.DepartmentEntity;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.model.DepartmentModel;
import com.xbongbong.sys.model.UserModel;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;

/**
 * @author 吴峰
 * @date 2022/03/17 14:08
 */
@Service("paasSubFormDataService")
public class PaasSubFormDataServiceImpl implements PaasSubFormDataService {

    private static final Logger LOGGER = LoggerFactory.getLogger(PaasSubFormDataServiceImpl.class);

    @Resource
    private PaasFormSubDataEsModel paasFormSubDataEsModel;

    @Resource
    private ProFormHelp proFormHelp;
    @Resource
    private UserModel userModel;
    @Resource
    private DepartmentModel departmentModel;
    @Resource
    private FormDataLinkDataListAnalysisDataHelp formDataLinkDataListAnalysisDataHelp;
    @Resource
    private IndexTypeModel indexTypeModel;

    @Override
    public SubFormDataListVO list(SubFormDataListDTO subFormDataListDTO) throws XbbException {
        try {
            Integer saasMark = subFormDataListDTO.getSaasMark();
            String corpid = subFormDataListDTO.getCorpid();
            Integer businessType = subFormDataListDTO.getBusinessType();
            Long formId = subFormDataListDTO.getFormId();
            String attr = subFormDataListDTO.getAttr();
            Long dataId = subFormDataListDTO.getDataId();
            PaasFormExplainEntity paasFormExplainEntity = proFormHelp.getExplainEntity(corpid, formId, businessType);

            Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMap(paasFormExplainEntity.getExplains(), null);
            if (!explainMap.containsKey(attr)) {
                return new SubFormDataListVO();
            }
            List<FieldAttrEntity> explainList = (List<FieldAttrEntity>) explainMap.get(attr).getSubForm().getItems();
            Set<String> userSet = new HashSet<>();
            Set<String> departmentSet = new HashSet<>();
            // 获取用户和部门的字段
            OrganizationFieldUtil.getUserAndDeptField(explainList, userSet, departmentSet);

            BoolQueryBuilder boolQueryBuilder = boolQuery();
            IndexTypeEnum indexTypeEnum = indexTypeModel.getSubIndexType(corpid, businessType, saasMark);

            boolQueryBuilder.filter(termQuery(StringConstant.CORPID + StringConstant.POINT + StringConstant.KEY_WORD, corpid));
            boolQueryBuilder.filter(termQuery(StringConstant.ATTR + StringConstant.POINT + StringConstant.KEY_WORD, attr));
            boolQueryBuilder.filter(termQuery(StringConstant.FORM_ID, formId));
            boolQueryBuilder.filter(termQuery(StringConstant.DATA_ID, dataId));

            XbbAggregatedPage<PaasFormDataEntityExt> xbbAggregatedPage = paasFormSubDataEsModel.list(boolQueryBuilder, indexTypeEnum, null, subFormDataListDTO.getPage(), subFormDataListDTO.getPageSize(), PaasFormDataEntityExt.class);
            List<PaasFormDataEntityExt> subDataList = xbbAggregatedPage.getContent();

            Set<String> userIdSet = new HashSet<>();
            Set<Long> deptIdSet = new HashSet<>();

            subDataList.forEach(item->{
                JSONObject data = item.getData();
                userIdSet.addAll(OrganizationFieldUtil.getUserId(data, userSet));
                deptIdSet.addAll(OrganizationFieldUtil.getDeptId(data, departmentSet));
            });

            List<UserEntity> userList = userModel.getByUserIdIn(corpid, userIdSet, false);
            Map<String, UserEntity> userMap = new HashMap<>(userList.size());
            userList.forEach(item->{
                userMap.put(item.getUserId(), item);
            });

            List<DepartmentEntity>  departmentList = departmentModel.getByDepIdIn(corpid, deptIdSet);
            Map<String, DepartmentEntity> departmentMap = new HashMap<>(departmentList.size());
            departmentList.forEach(item->{
                departmentMap.put(String.valueOf(item.getId()), item);
            });
            List<JSONObject> list = new ArrayList<>();
            FormDataListDTO formDataListDTO = new FormDataListDTO();
            BeanUtil.copyProperties(subFormDataListDTO, formDataListDTO);
            PaasFormDataEsListVO formDataListVO = new PaasFormDataEsListVO();
            formDataListVO.setPaasFormDataESList(subDataList);
            formDataListVO.setHeadList(explainList);
            formDataLinkDataListAnalysisDataHelp.analysisDataList(formDataListDTO, formDataListVO);

            formDataListVO.getPaasFormDataESList().forEach(item->{
                list.add(item.getData());
            });

            int num = (int) xbbAggregatedPage.getTotalElements();
            PageHelper pageHelper = PageHelperUtil.initPageHelper(num, subFormDataListDTO.getPage(), subFormDataListDTO.getPageSize(), PageConstant.DEFAULT_PAGE_SIZE);
            return new SubFormDataListVO(pageHelper, list);
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOGGER.error("com.xbongbong.paas.service.impl.PaasSubFormDataServiceImpl.list error", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }

    }
}
